package org.example.struct.array2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liyishan
 * @date 2023/9/11 11:31
 * @apiNote
 */

public class Test00056Merge {

    public int[][] merge(int[][] intervals) {
        int m = intervals.length;
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            int[] interval = intervals[i];
            if (list.size() == 0 || list.get(list.size() - 1)[1] < interval[0]) {
                list.add(interval);
            }else{
                list.get(list.size() - 1)[1] = Math.max(list.get(list.size() - 1)[1], interval[1]);
            }
        }
        //return list.toArray(new int[list.size()][2]);
        int[][] merge = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            merge[i] = list.get(i);
        }
        return merge;
    }
}
